#!/bin/bash

# 检查root权限
if [ "$(id -u)" != "0" ]; then
    echo "错误：必须使用root权限运行此脚本。"
    exit 1
fi

# 显示警告信息
echo "================================================"
echo " 警告：此操作将完全移除OpenVPN及其所有配置！"
echo "================================================"
echo
echo "将执行以下操作："
echo "1. 停止并禁用OpenVPN服务"
echo "2. 删除所有配置文件(/etc/openvpn)"
echo "3. 清理防火墙规则"
echo "4. 恢复系统网络设置"
echo "5. 可选卸载软件包"
echo

# 添加确认提示
read -p "确定要继续吗？(y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "操作已取消。"
    exit 0
fi

# 添加5秒倒计时
echo "将在5秒后开始清理，按Ctrl+C取消..."
for i in {5..1}; do
    echo -n "$i "
    sleep 1
done
echo
echo "开始清理..."

# 1. 停止并禁用服务
echo "[1/5] 停止OpenVPN服务..."
systemctl stop openvpn-server@server 2>/dev/null || true
systemctl disable openvpn-server@server 2>/dev/null || true

# 2. 删除文件和目录
echo "[2/5] 删除OpenVPN配置文件..."
rm -rf /etc/openvpn
rm -rf /usr/share/easy-rsa
rm -f /etc/systemd/system/multi-user.target.wants/openvpn-server@server.service

# 3. 清理防火墙
echo "[3/5] 清理防火墙规则..."
iptables -t nat -D POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE 2>/dev/null || true
iptables-save > /etc/iptables.rules 2>/dev/null || true

# 4. 恢复系统设置
echo "[4/5] 恢复系统设置..."
sed -i '/net.ipv4.ip_forward/s/^/#/g' /etc/sysctl.conf
sysctl -p >/dev/null 2>/dev/null || true

# 5. 可选：卸载软件包
echo "[5/5] 软件包处理..."
read -p "是否要卸载OpenVPN和easy-rsa软件包？(y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -x "$(command -v apt-get)" ]; then
        apt-get remove --purge -y openvpn easy-rsa
    elif [ -x "$(command -v yum)" ]; then
        yum remove -y openvpn easy-rsa
    fi
    echo "已卸载软件包。"
else
    echo "保留软件包。"
fi

echo "================================================"
echo " OpenVPN清理完成！"
echo "================================================"